package servlet.request;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-07-15
 * Time:17:57
 */
@WebServlet(name = "RequestServlet", urlPatterns = "/requestServlet")
public class RequestServlet extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        StringBuffer requestURL = req.getRequestURL();
        String remoteAddr = req.getRemoteAddr();
        String host = req.getHeader("Host");
        String referer = req.getHeader("Referer");
        String userAgent = req.getHeader("User-Agent");
        String username = req.getParameter("username");
        String password = req.getParameter("pwd");
        String[] sports = req.getParameterValues("sport");
        System.out.println("URI: " + uri);
        System.out.println("RequestURL: " + requestURL);
        System.out.println("RemoteAddr: " + remoteAddr);
        System.out.println("Host: " + host);
        System.out.println("Referer: " + referer);
        System.out.println("User-Agent: " + userAgent);
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
        for (String sport : sports) {
            System.out.println("SPORT: " + sport);
        }
        getBrowsers(req);
        getJSESSIONID(req);
    }

    private void getBrowsers(HttpServletRequest req) {
        String userAgent = req.getHeader("User-Agent");
        String[] strings = userAgent.split(" ");
        String[] browser = strings[strings.length - 1].split("/");
        System.out.println("Browser: " + browser[0]);
    }
    private void getJSESSIONID(HttpServletRequest req) {
        String header = req.getHeader("Cookie");
        System.out.println("JSESSIONID:" + header.split("[ =;]")[1]);

        Cookie[] cookies = req.getCookies();
        System.out.println(cookies[0].getName() + ":" + cookies[0].getValue());
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
